import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter_base/http/http_connection_check.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:flutter_base/utils/loading/loading_utils.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/utils/shared/shared_export.dart';

import 'config/app_routes.dart';

class Application {
  static final Application _instance = Application._();

  factory Application() => _instance;

  Application._();

  Future initialize() async {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom],
    );

    // 系统底部控制栏的颜色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.black,
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
    ));
    await LoadingUtils.setup();
    await SharedStorage().initShareStorage();
    await initialPrivacySDK();
    LoadingUtils.setup();
  }

  static String initialRoute() {
    // if (AppUserManager().token.isEmpty || AppUserManager().user.value == null) {
    //   return AppRoutes.login;
    // } else {
      return AppRoutes.testPage;
    // }
  }

  static void changeStatusBar(
      {Brightness statusBarIconBrightness = Brightness.dark}) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarIconBrightness: statusBarIconBrightness,
    ));
  }

  /// 错误信息打印
  void logSystemError() {
    FlutterError.onError = (errorDetails) {
      clog(errorDetails, tag: "error", always: true);
    };
    PlatformDispatcher.instance.onError = (error, stack) {
      clog("$error \n ${stack.toString()}", tag: "error", always: true);
      return true;
    };
  }

  Future<void> setupHttp() async {
    await AppConfig.setup();
    // 网络请求需要行为操作的code码处理
    HttpManager().errorCodeListener = httpErrorCodeListener;
    HttpConnectionCheck.checkNetWork();
  }

  Future<void> initialPrivacySDK() async {
    await setupHttp();
    // FlutterDeviceId().getDeviceId();
    // FlutterDeviceId
  }

  void httpErrorCodeListener(int? code) {
    code ??= 0;
    if ((code >= 400 && code < 500) ||
        (code == HttpCode.code10104 )) {
      /// 未登录不触发退出登录弹窗
      AppUserManager().logout();
    }
  }
}
